"""赠品功能"""

from odoo import models, api, fields
from odoo.tools import float_compare
from odoo.exceptions import UserError, ValidationError


class AccountMove(models.Model):
    _inherit = 'account.move'


    @api.model
    def create(self, val):
        res = super().create(val)
        return res

    @api.multi
    def write(self, val):
        res = super().write(val)
        return res


class AccountMoveLine(models.Model):
    _inherit = 'account.move.line'

    @api.model
    def default_get(self, fields):
        """满足客户要求:手动录入凭证自动填充标签内容."""
        rec = super().default_get(fields)
        if 'line_ids' not in self._context:
            return rec

        name = ''
        for line in self.move_id.resolve_2many_commands(
                'line_ids', self._context['line_ids'], fields=['name']):
            name = line.get('name', '')
        rec.update({'name': name})
        return rec

    @api.model
    def create(self, val):
        res = super().create(val)
        return res

    @api.multi
    def write(self, val):
        res = super().write(val)
        return res


class PurchaseOrder(models.Model):
    _inherit = 'purchase.order'


class PreAccountLine(models.Model):
    _inherit = 'pre.account.line'

    gift = fields.Boolean('赠品', compute="_compute_gift", store=True)

    @api.depends('sale_line_id', 'purchase_line_id', 'move_id')
    def _compute_gift(self):
        for order in self:
            if order.sale_line_id:
                order.gift = order.sale_line_id.gift
            elif order.purchase_line_id:
                order.gift = order.purchase_line_id.gift
            elif order.move_id.sale_line_id:
                order.gift = order.move_id.sale_line_id.gift
            elif order.move_id.purchase_line_id:
                order.gift = order.move_id.purchase_line_id.gift


class PurchaseOrderLine(models.Model):
    _inherit = 'purchase.order.line'

    gift = fields.Boolean('赠品')

    @api.model
    def create(self, val):
        """采购赠品的金额必定为0"""
        if val.get('gift') is True:
            val['price_unit'] = 0
        res = super().create(val)
        return res

    @api.multi
    def write(self, val):
        """采购赠品的金额必定为0"""
        if not self.env.context.get('bypass_gift_check'):   # 某些条件下需要跳过这个检查
            if self.gift or val.get('gift') is True:
                val['price_unit'] = 0
        res = super().write(val)
        return res


class SaleOrderLine(models.Model):
    _inherit = 'sale.order.line'

    gift = fields.Boolean('赠品')

    @api.model
    def create(self, val):
        """销售赠品的金额必定为0"""
        if val.get('gift') is True:
            val['price_unit'] = 0
        res = super().create(val)
        return res

    @api.multi
    def write(self, val):
        """销售赠品的金额必定为0 TODO???"""
        if not self.env.context.get('bypass_gift_check'):   # 某些条件下需要跳过这个检查
            if self.gift or val.get('gift') is True:
                val['price_unit'] = 0
        res = super().write(val)
        return res


class StockMoveExt(models.Model):
    _inherit = 'stock.move'

    nd_lot_text = fields.Char(compute="_compute_nd_lot_ids")

    def _compute_nd_lot_ids(self):
        """获取stock.move对应的批次号信息，便于打印"""
        for move in self:
            lot_names = move.move_line_ids.mapped('lot_id.name')
            move.nd_lot_text = "，".join(lot_names)

    def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id):
        # 赠品销售采购的科目需要修改
        self.ensure_one()
        rslt = super()._generate_valuation_lines_data(partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id)
        if self.purchase_line_id and self.purchase_line_id.gift:
            if self._is_return():
                credit_acc_id, debit_acc_id = self.env['product.category']._nd_get_gift_account(self.purchase_line_id)
            else:
                debit_acc_id, credit_acc_id = self.env['product.category']._nd_get_gift_account(self.purchase_line_id)
            rslt['credit_line_vals']['account_id'] = credit_acc_id.id
            rslt['debit_line_vals']['account_id'] = debit_acc_id.id
        elif self.sale_line_id and self.sale_line_id.gift:
            if self._is_return():
                credit_acc_id, debit_acc_id = self.env['product.category']._nd_get_gift_account(self.sale_line_id)
            else:
                debit_acc_id, credit_acc_id = self.env['product.category']._nd_get_gift_account(self.sale_line_id)
            rslt['credit_line_vals']['account_id'] = credit_acc_id.id
            rslt['debit_line_vals']['account_id'] = debit_acc_id.id
        return rslt

